package com.sky.config;

import com.sky.service.DishService;
import com.sky.service.SetmealService;
import com.sky.vo.DishVO;
import com.sky.vo.SetmealVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;

@Configuration
@Slf4j
public class CachePreloadConfig {

    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;

    //设置菜品缓存预热数量
    private static final int HOT_DISH_LIMIT = 10;
    //设置套餐缓存预热数量
    private static final int HOT_SETMEAL_LIMIT = 10;

    /**
     * 应用启动后执行：加载热门菜品到缓存（缓存预热）
     * 作用：避免启动后用户首次访问热门菜品时，缓存未命中导致查 DB
     */
    @Bean
    public ApplicationRunner cachePreloader() {
        return args -> {
            // 延迟几秒执行，等待数据库连接稳定
            Thread.sleep(5000);

            try {
                // 预加载热门菜品
                preloadHotDishes();

                // 预加载热门套餐
                preloadHotSetmeals();

            } catch (Exception e) {
                log.error("缓存预加载失败", e);
            }
        };
    }

    private void preloadHotDishes() throws InterruptedException {
        log.info("开始预加载热门菜品到缓存");

        List<Long> hotDishIds = dishService.getHotDishIds(HOT_DISH_LIMIT);
        log.info("获取到 {} 个热门菜品ID用于缓存预热", hotDishIds.size());

        for (Long id : hotDishIds) {
            try {
                DishVO dishVO = dishService.getByIdWithFlavor(id);
                if (dishVO != null) {
                    log.info("成功预加载热门菜品到缓存，菜品ID: {}", id);
                } else {
                    log.warn("菜品ID {} 不存在或已停售", id);
                }
                Thread.sleep(100);
            } catch (Exception e) {
                log.warn("预加载菜品ID {} 时出错: {}", id, e.getMessage());
            }
        }
        log.info("热门菜品缓存预加载完成");
    }

    private void preloadHotSetmeals() throws InterruptedException {
        log.info("开始预加载热门套餐到缓存");

        List<Long> hotSetmealIds = setmealService.getHotSetmealIds(HOT_SETMEAL_LIMIT);
        log.info("获取到 {} 个热门套餐ID用于缓存预热", hotSetmealIds.size());

        for (Long id : hotSetmealIds) {
            try {
                SetmealVO setmealVO = setmealService.getByIdWithDish(id);
                if (setmealVO != null) {
                    log.info("成功预加载热门套餐到缓存，套餐ID: {}", id);
                } else {
                    log.warn("套餐ID {} 不存在或已停售", id);
                }
                Thread.sleep(100);
            } catch (Exception e) {
                log.warn("预加载套餐ID {} 时出错: {}", id, e.getMessage());
            }
        }
        log.info("热门套餐缓存预加载完成");
    }

}
